<?php

/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author yuan1994 <tianpian0805@gmail.com>
 * @link http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
//------------------------
// 用户控制器
//-------------------------

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use app\common\model\Company;
use think\Db;
use think\Exception;
use think\Loader;
use think\Config;

class User extends Controller
{

    use \app\admin\traits\controller\Controller;
    protected $modelCompany;
    private $admin_reg;
    private $ucompanyModel;
    public function __construct()
    {
        parent::__construct();
        $this->model = $this->getModel();
        $this->modelCompany = $this->getModel('userCompany');
        $UserSpecialty = new \app\common\model\UserSpecialty(); //实例化专业
	       
        $SpecialtyList = $UserSpecialty->getList($_SESSION['think']['reg']); //获取专业列表
        
        $SpecialtyList = setArrKeyId($SpecialtyList);

        $Project = new \app\common\model\Project(); //实例化 项目
        $ProjectList = $Project->getList($_SESSION['think']['reg']); //获取项目列表
        $ProjectList = setArrKeyId($ProjectList);

		$arr = array('0'=>'无项目组');
		foreach($ProjectList as $vc){
			$arr[$vc['id']] = $vc['name'];
		}

        $Company = new \app\common\model\Company(); //实例化 公司
        $CompanyList = $Company->getList($_SESSION['think']['reg']); //获取公司列表
        $CompanyList = setArrKeyId($CompanyList);

        $Department = new \app\common\model\Department(); //实例化 部门
        $dments = $Department->getList($_SESSION['think']['reg']); //获取部门列表
        $dments = setArrKeyId($dments);
        //注册时间列表
        $UserModel = new \app\common\model\User();
        $timeList = $UserModel->getUserRegTimeList();

        $this->ucompanyModel =  new \app\common\model\UserCompany();

        $this->admin_reg = $_SESSION['think']['reg'];
        $this->view->assign('timeList', $timeList);
        $this->view->assign('specialtyList', $SpecialtyList);
        $this->view->assign('ProjectList', $ProjectList);
		$this->view->assign('projectname', $arr);
        $this->view->assign('CompanyList', $CompanyList);
        $this->view->assign('dments', $dments);
		
    }

    protected function filter(&$map)
    {
        $realname = $this->request->param('realname');
        if ($realname)$map['realname'] = ["like", "%" . $realname . "%"];

        $username = $this->request->param('username');
        if ($username)$map['username'] = ["like", "%" . $username . "%"];

        $email = $this->request->param('email');
        if ($email)$map['email'] = ["like", "%" . $email . "%"];

        $phone = $this->request->param('phone');
        if ($phone)$map['phone'] = ["like", "%" . $phone . "%"];    

        $companyName = $this->request->param('companyname');

        if ($companyName && strpos($companyName,'输入公司名称') === false)$map['b.company_name'] = ["like", "%" . $companyName . "%"];

        $specialtyid = $this->request->param("specialtyid");

        if($this->request->param("projectname_id") && $this->request->param("projectname_id")!='99999999999a'){
            $map['b.groupid'] = (int)$this->request->param("projectname_id");
        }
         $vface = $this->request->param("vface");

		if($vface){           
           if($vface == 'no') $vface =0;
		   unset($map['vface']);
            $map['a.vface'] = $vface;
        }
		
		 if($this->request->param("idcard")){
            $map['idcard'] = ["like", "%" . trim($this->request->param("idcard")) . "%"];
        }
       
       
        if ($specialtyid)  $map['b.specialty_id'] = $specialtyid;
        $companyid = $this->request->param("companyid");
        if ($companyid)  $map['b.company_id'] = $companyid;
        $dmentsid = $this->request->param("dmentsid");
        if ($dmentsid)  $map['departmentid'] = $dmentsid;
        $Projectid = $this->request->param("Projectid");
        if ($Projectid)  $map['project_id'] = $Projectid;
        $userregtime = $this->request->param("userregtime");
        if ($userregtime)  $map['userregtime'] = $userregtime;
    }

    /**
     * 首页
     * @return mixed
     */
    public function index() 
    {

		include_once(dirname(dirname(__FILE__)).'/per_config.php');

        $model = $this->getModel();
		$child_plaform = getChildAdminRegByPlaformId($this->plaform);
	   // var_dump($child_plaform);exit;
		$marks = '';
		if(in_array('j9f1z5co_7c670u8lkl9z59f7edb7ebd23taowei',$child_plaform) || in_array('j4timvso_54lkl9x3flob595f327ba4cb3gdl_test',$child_plaform)){
			$marks = 'jb'; 
		}
        // 列表过滤器，生成查询Map对象
        $map = $this->search($model);
        $map['_field'] = 'a.userid,a.realname,a.username,b.plaform_id,a.idcard,a.photo_collect,a.vface,b.company_name,b.position,b.groupid,b.departmentid,b.departmentgroupid,b.specialty_id,b.contact_phone,b.id,b.status,a.phone';
       // $map['b.admin_reg'] = $_SESSION['think']['reg'];
	    $map['b.admin_reg'] = ['in',$child_plaform];
        $map['b.isdelete'] = $this::$isdelete;
        //部门vface
        $getdepartmentid = $this->request->param("vfaceid");
        if(isset($getdepartmentid) && $getdepartmentid!=''){
            $map['a.departmentid'] = $getdepartmentid;
        }
		//$map['a.departmentidcc'] = 1;
        // 年龄段查询 sunman
        $start_age = $this->request->param("start_age");
        $end_age = $this->request->param("end_age");
        if($start_age && $end_age){
            // 将年龄转换成2017日期格式
            // 用between 查询区间
            $agelist = $this->returnDateString($start_age,$end_age);
            if($agelist){
                foreach ($agelist as $key=>$value) {
                    $mapwhere[] = ["like", "%" . $value. "%"];    
                }
                $map['a.idcard'] = array($mapwhere,'or');
            } 
        }
		
		//$child_plaform = getChildAdminRegByPlaformId($this->plaform);
		$Plaform_name = array();
		$Plaform = new \app\common\model\Plaform(); //实例化平台
		$planame = $Plaform->where(['admin_reg'=>['in',$child_plaform]])->field('real,id')->select();
		foreach($planame as $vname){
			$Plaform_name[$vname->id] = $vname->real;
			
		}
		
        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $modelSystemSetting = new \app\common\model\SystemSetting();
        $isAllowEdit = $modelSystemSetting->field('value')->where("`name`='userInfoAllowEdit'")->select();
        $isAllowEdit = $isAllowEdit[0]['value'];

        // $AdminRole = new \app\common\model\AdminRole(); //实例化 角色
        // $adminRole = $AdminRole->getUserRoleList(); //获取 角色列表
        $map['_func'] = function ($model) {$model->alias('a')->join("agk_user_company b","b.userid = a.userid",'left')->order('b.id desc'); }; 
        $this->datalist($model, $map); 
        var_dump($map);exit;
		$Department = new \app\common\model\Department(); //实例化 部门
		$dments = $Department->getList($_SESSION['think']['reg']); //获取部门列表
		$division = array();
		foreach($dments as $v){
			$division[$v->id] = $v->name;
		}

        $this->view->assign('isAllowEdit', $isAllowEdit);
		$this->view->assign('team_shows', $perconfig['team_shows']);
        // $this->view->assign('adminRole', $adminRole);
		$this->view->assign('division', $division);
		$this->view->assign("Plaform_name", $Plaform_name);
		$this->view->assign("team_shows", $marks);
        return $this->view->fetch();
    }

    public function getRolenameByUid()
    {
        $AdminRole = new \app\common\model\AdminRole(); //实例化 角色
        $adminRole = $AdminRole->getUserRoleList(); //获取 角色列表
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();
        if ($this->request->isPost()) {
            $data = $this->request->post();
		
			$arr = ['idcard'=>$data['user']['idcard']];
			$userdeDetails = cur_post('serviceApi/member/getUserInfoByidcard',1,$arr,1 );
	
			if(!$userdeDetails->code){
				return ajax_return_error('未找到指定用户'); 
			}
			
            $userData = $data['user'];
            $userCompanyData = $data['usercompany'];
			$userData['realname'] = $userdeDetails->data->username;
            //if(!$data['companyid']) return ajax_return_error('请选择公司!'); 

            $UserModel = new \app\common\model\User();
            $userCompany['companyName'] = Db::name('Company')->where(['id'=>$userCompanyData['companyid'],'admin_reg' => $this->admin_reg, 'isdelete' => 0, 'status' => 1])->value('name');

            try {
                $userData['admin_reg'] = $this->admin_reg;
                $userData['userregtime'] = time();
                $userData['logtime'] = time();                                                                
                $userData['password'] = empty($userData['password']) || $userData['password']!='nonepassword' ? Config::get('site.default_password') : $userData['password'];
               //密码加密
               $userData['passsalt'] = self::random(8);
               $userData['password'] = self::dpassword($userData['password'], $userData['passsalt']);
				$userData["email"] = $userdeDetails->data->email;
                try {
                    $model = Db::name($this->parseTable($controller));
                    //处理是否存在，如果存正只需要导入到该平台
                    $user = $UserModel->getUserInfoByIdcard($userData['idcard']);

                    //如果用户不存在新增加用户到用户中心        
                    if (empty($user)) {
                        $res = $this->model->isUpdate(false)->allowField(true)->save($userData);
                        $user['userid'] = $model->getLastInsID();                        
                    }

                    $user = $UserModel->where(['userid'=>$user['userid']])->find();



                    //用户身份不存在增加
                    $whereIdentity = array('userid' => $user['userid'], 'admin_reg' => $this->admin_reg);

                    $indentity = $this->ucompanyModel->where($whereIdentity)->find();           
                    if(empty($indentity['id'])){
                        $userCompanyData['userid'] =$user['userid'];
                        $userCompanyData['plaform_id'] = $this->plaform;
                        $userCompanyData['admin_reg'] = $this->admin_reg;
                        $userCompanyData['update_time'] = time();
                        $userCompanyData['status'] = 0;
                        $userCompanyData['company_name'] = $this->getModel('company')->where(['id'=>$userCompanyData['company_id']])->value('name');
                        $userCompanyData['specialty'] = $this->getModel('userspecialty')->where(['id'=>$userCompanyData['specialty_id']])->value('name');

                        
                        $ret =  $this->ucompanyModel->allowField(true)->save($userCompanyData);
                        $identity_id =  $this->ucompanyModel->getLastInsID();
                    }  
                    else{
                         $identity_id = $indentity['id'];
                    } 

                    $indentity = $this->ucompanyModel->where($whereIdentity)->find();

                    //是否已存入档案表
                    if (!empty($user)) {
                        $ar = Db::name('archives_user')->where(['identity_id'=>$identity_id])->find();
                        if (empty($ar)){
                            $ar_data['userid'] = $user['userid'];
                            $ar_data['identity_id'] = $identity_id;
                            $ar_data['username'] = $user['username'];
                            $ar_data['realname'] = $user['realname'];
                            $ar_data['idcard'] = $user['idcard'];
                            $ar_data['phone'] = $user['phone'];
                            $ar_data['photo_collect'] = $user['photo_collect'];
                            $ar_data['group'] = $indentity['groupid'];
                            $ar_data['specialty'] = $indentity['specialty_id'];
                            $ar_data['company_name'] = $indentity['company_name'];
                            $ar_data['plaform_id'] = $this->plaform;
                            $ar_data['admin_reg'] = $this->admin_reg;
                            $ret = Db::name('archives_user')->insert($ar_data);
                        }
                    }


                } catch (\Exception $e) {
                    return ajax_return_error($e->getMessage());
                }
                return ajax_return_adv('添加成功');
            } catch (Exception $ex) {
                \SLogger::getLogger('pub_thrift_service', 'thrift_error')->error('thrift call error', $ex);
            }
        } else {

            $Specialty = new \app\common\model\UserSpecialty(); //实例化 专业
            $Department = new \app\common\model\Department(); //实例化 部门
            $AdminPosition = new \app\common\model\AdminPosition(); //实例化 岗位
            $group = new \app\common\model\Project(); //实例化 部门
            $SpecialtyList = $Specialty->getList($_SESSION['think']['reg']); //获取专业列表
            $groupList = $group->getList($_SESSION['think']['reg']); //获取部门列表
            $ProjectList = generateTree($ProjectList, 0, 0);
            unset($tree);
            $this->view->assign('specialtyList', $SpecialtyList);
            $this->view->assign('groupList', $groupList);
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isPost()) {


            // 更新
            $data = $this->request->post();                        
            $userData = $data['user'];
            $userCompanyData = $data['usercompany'];


            //验证身份证是否重复
            
            if (isset($userData['idcard'])) $condition = ['idcard'=>$userData['idcard'],'userid'=>['<>',$data['userid']]];
            $result = Db::name('user')->where($condition)->field('userid')->find();
            if ($result) return ajax_return_adv_error('身份证已存在');
            if (!$data['userid']) return ajax_return_adv_error("缺少参数ID"); 

            try {

                $UserModel = new \app\common\model\User();

                $user = $UserModel->getUserInfoByIdcard($userData['idcard']);

                $passwordOld = $user['password'];
                $passsalt = $user['passsalt'];
                $passwordNew = $userData['password']!='nonepassword' ? self::dpassword($userData['password'], $passsalt) : $passwordOld;
                if($passwordOld != $passwordNew) $userData['password'] = $passwordNew; 
                $user['userid'] = $data['userid'];
                $user = $UserModel->where(['userid'=>$user['userid']])->find();


                //如果用户存在新更新用户到用户中心        
                if (!empty($user)) {
                    $res = $this->model->allowField(true)->where(['userid'=>$user['userid']])->update($userData);    

                }

                //修改用户身份信息

                $userCompanyData['userid'] =$user['userid'];
                $userCompanyData['plaform_id'] = $this->plaform;
                $userCompanyData['admin_reg'] = $this->admin_reg;
                $userCompanyData['update_time'] = time();
                $userCompanyData['status'] = 0;
                $userCompanyData['company_name'] = $this->getModel('company')->where(['id'=>$userCompanyData['company_id']])->value('name');
                $userCompanyData['specialty'] = $this->getModel('userspecialty')->where(['id'=>$userCompanyData['specialty_id']])->value('name');                        
               
                $ret =  $this->ucompanyModel->isUpdate(true)->allowField(true)->where(['userid' => $user['userid'], 'admin_reg' => $this->admin_reg])->update($userCompanyData);



            } catch (\Exception $e) {
                return ajax_return_error($e->getMessage());
            }
            return ajax_return_adv('保存成功');    

        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }


            $Specialty = new \app\common\model\UserSpecialty(); //实例化 专业
            $Project = new \app\common\model\Project(); //实例化 组
            $SpecialtyList = $Specialty->getList($_SESSION['think']['reg']); //获取专业列表

            $groupList = $Project->getList($_SESSION['think']['reg']); //获取组列表
            $groupList = generateTree($groupList, 0, 0);

            $Department = new \app\common\model\Department(); //实例化 部门
            $dments = $Department->getList($_SESSION['think']['reg']); //获取部门列表
            $Company = new \app\common\model\Company(); //实例化 部门
            $CompanyList = $Company->getList($_SESSION['think']['reg']); //获取部门列表

            $userData = $this->getModel('user')->where(['userid'=>$id])->find();
            $userCompanyData = $this->getModel('UserCompany')->where(['userid'=>$id,'admin_reg'=>$this->admin_reg])->find();

            //获取部门下属分组
            if(isset($userCompanyData['departmentid'])){
                $departmentGroup = $Department->getGroupList($userCompanyData['departmentid']);
                $this->view->assign("dgrouplist", $departmentGroup);   
            }
            
            $this->view->assign('specialtyList', $SpecialtyList);
            $this->view->assign('groupList', $groupList);
            $this->view->assign('CompanyList', $CompanyList);
            $this->view->assign('dments', $dments);
            $this->view->assign("user", $userData);
            $this->view->assign("usercompany", $userCompanyData);
			
            return $this->view->fetch();
        }
    }

    /**
     * 通过项目id获取公司列表
     *
     */
    public function getCompanyByProjectId() 
    {
        $ProjectId = $this->request->param('project_id');
        $Company = new \app\common\model\Company(); //实例化 部门
        $List = $Company->getListByProjectId($ProjectId, $_SESSION['think']['reg']);
        return $List;
    }

    /**
     * 通过项目id获取公司列表
     *
     */
    public function getOnSpecialtyByProjectId()
    {
        $ProjectId = $this->request->param('project_id');
        $Project = new \app\common\model\Project(); //实例化 部门
        $List = $Project->getListByArgOne(['admin_reg' => $_SESSION['think']['reg'], 'id' => $ProjectId], 'on_specialty');
        return $List;
    }

    /**
     * 通过公司id获取部门列表
     *
     */
    public function getDepartmentByCompanyId()
    {
        $Company_id = $this->request->param('company_id');
        // $Department = new \app\common\model\Department(); //实例化 部门
        // $List = $Department->getListByCompanyId($Company_id, $_SESSION['think']['reg']);


        // return $List;
        // 查询部门 pid为零为部门 不为零为部门下属分组
        $departmentList = Db::name('department')->where(['isdelete'=>0,'status'=>1,'pid'=>0,'company_id'=>$Company_id])->field('id,name,pid')->select();
        return $departmentList;
    }

    /**
     * 通过部门id获取职位
     *
     */
    public function getGroupByDepartmentId() 
    {
        $department_id = $this->request->param('department_id');
        $AdminPosition = new \app\common\model\AdminPosition(); //实例化 岗位
        $List = $AdminPosition->getListByDepartmentId($department_id, $_SESSION['think']['reg']);
        return $List;
    }

    /**
     * 通过部门id departmentid获取下属分组 
     * @author sunman
     */
    public function getCompanyGroupList(){
        $departmentid = $this->request->param('department_id');
        if(empty($departmentid)) ajax_return_adv_error("请先选择部门！");
        // pid 等于departmentid
        $groupList = Db::name('department')->where(['isdelete'=>0,'status'=>1,'pid'=>$departmentid])->field('id,name,pid')->select();
        // $groupList = setArrKeyId($groupList);
        return $groupList;
    }

    /**
     * 修改密码
     */
    public function password()
    {
        
        $id = $this->request->param('id/d');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $user_list = Loader::model('user_company')->getListByArgOne(array('userid' => $data['userid'],'admin_reg'=>['in',$child_plaform]));
            if(empty($user_list)){
                throw new Exception("缺少必要参数");
            }
            $pwd =md5((md5(md5($data['password']))) . $user_list['passsalt']);
            $re = Db::name('user_company')->where(['id' => $user_list['id']])->update(['password' => $pwd]);
            if ($re) {
                return ajax_return_adv('修改成功');
            } else {
                return ajax_return_error('修改失败');
            }
        } else {
            // 禁止修改管理员的密码，管理员 id 为 1
            if ($id < 2) {
                throw new Exception("缺少必要参数");
            }
            $this->view->assign('id', $id);
            return $this->view->fetch();
        }
    }

    public function ajaxUserPhoto(){
        $userid = $this->request->param('userid');
        $user_list = Loader::model('User')->getListByArgOne(array('userid' => $userid),'photo_collect,userid');
        return json_encode($user_list);
    }

    public function noPass(){
        $userid = $this->request->param('identity_id');
        $info = Loader::model('user')->updateVerifyPhoto(null,$userid,1);
        if ($info){
            return json_encode(['code'=>1,'msg'=>'成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'失败']);
        }

    }

    public function nopassPhoto(){
        $userid= $this->request->param('userid');
		if($userid==''){
			$userid= $this->request->param('identity_id');
			
		}
        $re = Loader::model('user')->updateVerifyPhoto(null,$userid,1);

        if ($re){
            return json_encode(['code'=>1,'msg'=>'成功']);
        }else{
            return json_encode(['code'=>0,'msg'=>'失败']);
        }
    }

    /**
     * 审核留底照片
     */
    public function verifyPhoto(){
        $userid = $this->request->param('userid');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $photo['photo'] = $data['photo'];
            $result = Loader::model('user')->updateVerifyPhoto($photo,$data['userid'],2);
            return ajax_return_adv('修改成功');
        } else {
            $info = Loader::model('user')->getVerifyPhotoById($userid);
            $this->view->assign('id', $userid);
            $this->view->assign('info', $info);
            return $this->view->fetch();
        }
    }
    /**
     * 禁用限制
     */
    protected function beforeForbid()
    {
        // 禁止禁用 Admin 模块,权限设置节点
        $this->filterId(1, '该用户不能被禁用', '=');
    }

    /**
     * 批量导入
     */
    public function batchimport()
    {
        if ($this->request->isAjax()) {
            $file = $this->request->param('file');
            $project = $this->request->param('project');
            $company = $this->request->param('company');
            if (!$file) {
                return "缺少文件路径参数";
            }
            if (!$project) {
                return "缺少项目组，请选择";
            }
            $file = dirname(dirname(dirname(dirname(__FILE__)))) . "/public" . $file;

            if (file_exists($file) && in_array(get_extension($file), array('xls', 'xlsx'))) {
                // 将 $excelHeader 数据抛给前端，让用户选择对应关系，然后再返回给后台进行对应数据的解析，例如抛给后台的数据如下 , 'F' => 'password', 'G' => 'password', 'H' => 'password', 'I' => 'password', 'J' => 'password'

                $header = ['A' => 'realname', 'B' => 'username', 'C' => 'password', 'D' => 'email', 'E' => 'phone', 'F' => 'company','G'=>'idcard'];
                $result = \Excel::parse($file, $header, 20, function ($data) {
                            Db::startTrans();
                            try {
                                $CompanyModel = new Company();
                                $UserModel = new \app\common\model\User();
                                $company = $this->request->param('company');
                                $project = $this->request->param('project');
                                $specialtyid = $this->request->param('specialtyid');
                                $DATEA = time();
                                foreach ($data as $k => &$v) {
                                    $v['username'] = trim($v['username']);
                                    $v['realname'] = trim($v['username']);
                                    $password = trim($v['password']);
                                    if ($v['username'] == '' || $v['password'] == '' || !isset($v['username']) || !isset($v['password'])) {
                                        unset($data[$k]);
                                        continue;
                                    }

                                    if ($company) {
                                        $companyList = $CompanyModel->getComanyIsExistByCompanyName($company, $project);
                                    } else {
                                        $companyList = $CompanyModel->getComanyIsExistByCompanyName($v['company'], $project);
                                    }

                                    if (empty($companyList['id'])) {
                                        continue;
                                    }
                                    $user = $UserModel->getUserInfoByIdcard($v['idcard']);

                                    if ($user) {//用户存在
                                        $whereIdentity = array(
                                            'userid' => $user['userid'],
                                            'admin_reg' => $_SESSION['think']['reg'],
                                            'status' => 0
                                        );
                                        $indentity = Db::name('user_company')->where($whereIdentity)->field('id,userid,company_name')->find();
                                        if ($indentity['id']) {
                                            $insertOffline = array(
                                                'userid' => intval($user['userid']),
                                                'username' => $user['username'],
                                                'idcard' => $v['idcard'],
                                                'previous_id' => intval($indentity['id']),
                                                'previous_identity' => $indentity['company_name'],
                                                'after_identity' => $companyList['name'],
                                                'admin_id' => intval($_SESSION['think']['auth_id']),
                                                'admin_reg' => $_SESSION['think']['reg'],
                                                'create_time' => $this->time
                                            );
                                            $ret = Db::name('user_offline')->insert($insertOffline);
                                        }
                                        $insert['userid'] = $user['userid'];
                                        $insert['plaform_id'] = $this->plaform;
                                        $insert['passsalt'] = self::random(8);
                                        $insert['password'] = self::dpassword($v['password'], $insert['passsalt']);
                                        $insert['company_id'] = $companyList['id'];
                                        $insert['company_name'] = $companyList['name'] ? $companyList['name'] : '';
                                        $insert['admin_reg'] = $_SESSION['think']['reg'];
                                        $ret = Db::name('user_company')->insert($insert);
                                    } else {
                                        $v['groupid'] = 0;
                                        $v['departmentid'] = 0;
                                        $v['userregtime'] = &$DATEA;
                                        $v['logtime'] = &$DATEA;
                                        $v['update_time'] = &$DATEA;
                                        $v['specialty_id'] = $specialtyid ? $specialtyid : '';
                                        $v['phone'] = (int)$v['phone'];
                                        $v['company'] = (string)$v['company'];
                                        $v['project_id'] = $project;
                                        $v['admin_reg'] = $_SESSION['think']['reg'];
                                        $v['status'] = 1;
                                        unset($data[$k]['password']);
                                        $uid = Db::name('user')->insert($v, TRUE, TRUE);

                                        if ($uid) {
                                            $insert['userid'] = $uid;
                                            $insert['plaform_id'] = $this->plaform;
                                            $insert['passsalt'] = self::random(8);
                                            $insert['password'] = self::dpassword($password, $insert['passsalt']);
                                            $insert['company_id'] = $companyList['id'];
                                            $insert['company_name'] = $companyList['name'] ? $companyList['name'] : '';
                                            $insert['admin_reg'] = $_SESSION['think']['reg'];
                                            $ret = Db::name('user_company')->insert($insert);
                                            if (!$ret){
                                                $ar_data['userid'] = $uid;
                                                $ar_data['identity_id'] = $ret;
                                                $ar_data['username'] = $data['username'];
                                                $ar_data['realname'] = $data['realname'];
                                                $ar_data['idcard'] = $data['idcard'];
                                                $ar_data['phone'] = $data['phone'];
                                                $ar_data['photo_collect'] = $data['photo_collect'];
                                                $ar_data['group'] = $data['project_id'];
                                                $ar_data['specialty'] = $data['specialty_id'];
                                                $ar_data['company_name'] = $companyList['name'] ? $companyList['name'] : '';
                                                $ar_data['plaform_id'] = $this->plaform;
                                                $ar_data['admin_reg'] = $_SESSION['think']['reg'];
                                                $ret = Db::name('archives_user')->insert($ar_data);
                                            }
                                        }
                                    }
                                }
                                // 提交事务
                                Db::commit();
                            } catch (\Exception $e) {
                                // 回滚事务
                                Db::rollback();
                                return ajax_return_adv_error($e->getMessage());
                            }
                        });
                echo 'y';
            } else {
                return "文件不存在或不合法";
            }
        } else {
            $department = Db::name('department')->field('id,name,remark')->where(1)->select();
            $Specialty = new \app\common\model\UserSpecialty(); //实例化 专业
            $Department = new \app\common\model\Department(); //实例化 部门
            $project = new \app\common\model\Project(); //实例化 项目

            $dments = $Department->getList($_SESSION['think']['reg']); //获取部门列表
            $trees = generateTreeOne($dments, 0);
            $cject = $project->getList($_SESSION['think']['reg']); //获取项目列表
            $cject = generateTreeOne($cject, 0, 0);
            $SpecialtyList = $Specialty->getList($_SESSION['think']['reg']); //获取专业列表

            $this->view->assign('specialtyList', $SpecialtyList);
            $this->view->assign('cject', $cject);
            $this->view->assign('tree', $trees);

            $this->view->assign("department", $department);
            return $this->view->fetch();
        }
    }

    public function batchimport1() 
    {
        $Department = new \app\common\model\Department(); //实例化 部门
        $AdminPosition = new \app\common\model\AdminPosition(); //实例化 岗位

        $dments = $Department->getList($_SESSION['think']['reg']); //获取部门列表
        $trees = generateTree($dments, 0, 0);
        $aPosition = $AdminPosition->getList($_SESSION['think']['reg']); //获取岗位列表
        $aPosition = generateTree($aPosition, 0, 0);
        var_dump($aPosition);
        exit;
    }

    public function ajaxChangeAllow() 
    {
        $allow = $this->request->param('allow');
        if (is_numeric($allow) && in_array($allow, array('1', '0'))) {
            $modelSystemSetting = Db::name('system_setting');
            $ret = $modelSystemSetting->where('name', 'userInfoAllowEdit')->update(array('value' => $allow));
            if ($ret)
                return 1;
            else
                return 0;
        } else {
            return 0;
        }
    }


    /**
     * 清空回收站
     */
    public function clearUser()
    {
        $model = $this->getModel();$child_plaform = getChildAdminRegByPlaformId($this->plaform);

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, ['a.'.$this->fieldIsDelete => $this::$isdelete,'a.'.$this->fieldReg => ['in',$child_plaform]]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $where[$this->fieldIsDelete] = 1;
        $return = $model->where($where)->delete();
        if ($return) {
            return ajax_return_adv("清空回收站成功");
        }else{
            return ajax_return_adv_error('请选择清空回收站内容');
        }
    }
    public function batchDelete(){
        //人员列表
        $model = $this->getModel();$child_plaform = getChildAdminRegByPlaformId($this->plaform);

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, ['a.'.$this->fieldIsDelete => $this::$isdelete,'a.'.$this->fieldReg => ['in',$child_plaform]]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }
        if ($map['company_id']){
            $map['a.company_id'] = $map['company_id'];
            unset($map['company_id']);
        }
        $map['_field'] = 'a.userid,a.realname,a.username,a.idcard,a.userregtime,a.company,a.company_id,a.specialty,a.specialty_id,a.project_id,a.departmentid,b.name as projectname,c.name as departmentname';
        $map['a.admin_reg']=$_SESSION['think']['reg'];
        $map['a.isdelete'] = 0;
        $map['a.status'] = 1;
        $map['_func'] = function ($model) {$model->alias('a')
            ->join("project b","a.project_id = b.id AND b.isdelete = 0 AND b.status= 1",'left')
            ->join("department c","a.departmentid = c.id",'left')
            ->group('a.userid'); };

        $Lists = $this->datalist($model, $map,$field = null, $sortBy = '', false,true,true);

        $addtime = [];
        $this->view->assign("count", $Lists->total());
        $this->view->assign('numPerPage', $Lists->listRows());
        $this->view->assign("page", $Lists->render());
        $this->view->assign('Lists', $Lists);
        return $this->view->fetch();
    }
    
    /**
     * 失效人员管理
     * @return type
     */
    public function offline()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $id = $this->request->param('pid');
            $oid = $this->request->param('oid');

            $res = Db::name('user_company')->where("id={$id}")->update(array('status' => 1));
            
            if($res){
                $ret = Db::name('user_offline')->where("id={$oid}")->update(array('status'=> 1));
                if(!$ret){
                    return ajax_return(array(),'操作失效失败,请稍候失败', 1);
                }
            } else {
                return ajax_return(array(),'操作失效失败,请稍候失败', 1);
            }
            return ajax_return(array(), '操作失效成功',0);
        } else {

            $model = Db::name('user_offline');
            $where = array(
                'admin_reg' => $_SESSION['think']['reg'],
                'status' => 0
            );
            $field = 'id,userid,username,idcard,previous_id,previous_identity,after_identity,status,create_time';
            $record = $model->where($where)->field($field)->order('id desc')->paginate(20);
            $count = $model->where($where)->field($field)->count();
            $page = $record->render();

            $this->view->assign('record', $record);
            $this->view->assign('page', $page);
            $this->view->assign('count', $count);
            return $this->view->fetch();
        }
    }

    /**
     * 取得与主站密码相同算法的密钥
     * @access private
     * @param type $length
     * @param type $type
     * @param type $hash
     * @return string
     */
    private static function random($length, $type = 0, $hash = '') 
    {
        if ($type == 0) {
            $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        } else if ($type == 1) {
            $chars = '0123456789';
        } else if ($type == 2) {
            $chars = 'abcdefghijklmnopqrstuvwxyz';
        }
        $max = strlen($chars) - 1;
        mt_srand((double) microtime() * 1000000);
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     * 取得与主站相同算法的密码
     * @access private
     * @param type $password
     * @param type $salt
     * @return type
     */
    private function dpassword($password, $salt)
    {
        /* 老平台转密码验证 */
        if ($salt == 'aa123456') {
            return '' === $password ? '' : md5(sha1($password) . '*]f)={.zRuS;FZWUv6"TGJPO_5g<Kx#~k&|7nj(I');
        } else {
            return md5((preg_match("/^[a-f0-9]{32}$/", $password) ? md5($password) : md5(md5($password))) . $salt);
        }
    }

    /*回收站管理*/
    public function recyclebin(){
        $this::$isdelete = 1;
        $origin = $_SERVER['REQUEST_URI'];
        $min = stripos($origin,'.');
        if($min>1){
            $origin = substr($origin,0,$min).'.html';
        }
        $origin = str_replace('recyclebin','index',$origin);
        $this->view->assign("origin", $origin);
        return $this->index();
    }

    /**
     * 默认删除操作
     */
    public function delete()
    {

        $id = $this->request->param('id');
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        $result = $this->modelCompany->where($whereSql)->update(['isdelete'=>1]);
        $msg = $result ? '移动到回收站成功':'移动到回收站失败';
        return ajax_return_adv($msg);
    }

    /**
     * 从回收站恢复
     */
    public function recycle()
    {
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        $result = $this->modelCompany->where($whereSql)->setField('isdelete',0);
        $msg = $result >0 ? '恢复成功':'恢复失败';
        return ajax_return_adv($msg);
    }
	
	
	/*
     * 导出excel
     */
    public function userexcel()
    {
	$id = $this->request->param('id');
        if ($id == '') {
            #throw new HttpException(404, '该记录不存在');
            echo json_encode(['code' => 'n', 'msg' => '记录不存在']);
            exit;
        }
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $UserCompany = new \app\common\model\UserCompany();
        $examInfo = $UserCompany->getListByArgAll(['a.admin_reg' => ['in', $child_plaform], 'a.isdelete' => 0, 'b.realname' => ['NEQ', '']], 'a.company_name,a.groupid,b.realname,b.phone,b.idcard,a.specialty,a.position,b.username,b.company,b.vface');
        $header = ['姓名', '公司名', '手机号', '身份证', '分组', '职位', '专业', '留底照片']; //'参加考试时间','身份证号',
        $file_add = dirname(dirname(dirname(dirname(__FILE__)))) . '/public/static/admin/excel/' . $_SESSION["think"]["auth_id"] . '/';
        if (!file_exists($file_add)) {
            mkdir($file_add, 0777, true);
        }

        //读取分组项目信息  by yanghao 2018-01-16
        $Project = new \app\common\model\Project(); //实例化 项目
        $ProjectList = $Project->getList($_SESSION['think']['reg']); //获取项目列表
        $ProjectList = setArrKeyId($ProjectList);

        $arr = array('0' => '无项目组');
        foreach ($ProjectList as $vc) {
            $arr[$vc['id']] = $vc['name'];
        }

        $data = array();
        foreach ($examInfo as $v) {
            if ($v['vface'] == 2) {
                $face = '已通过';
            } else if ($v['vface'] = 1) {
                $face = '未审核';
            } else {
                $face = '未上传';
            }
            
            //EXCEL增加 分组 专业 留底照片审核信息 by yanghao 2018-01-16
            $data[] = [
                'truename' => empty($v['realname']) ? $v['username'] : $v['realname'],
                'company' => empty($v['company_name']) ? $v['company'] : $v['company_name'],
                'phone' => $v['phone'],
                'idcard' => '|' . $v['idcard'],
                'groupid' => $arr[$v['groupid']],
                'position' => $v['position'],
                'specialty' => $v['specialty'],
                'vface' => $face
            ];
        }

        /* 	if ($error = exportexcel($data,$header, $vo[0]['ep_paper_name']."考试成绩导出")) {
          //因为无法使用输出缓冲区 用临时方法解决
          throw new Exception($error);
          }
         */

        if ($data) {
            if ($error = \Excel::export_file($header, $data, 'PersonnelExport', '2007', $file_add, 'excel')) {
                //因为无法使用输出缓冲区 用临时方法解决

                if ($error['code']) {
                    return ['code' => 'y', 'addres' => 'http://' . $_SERVER['HTTP_HOST'] . '/static/admin/excel/' . $_SESSION["think"]["auth_id"] . '/' . $error['addrs'], 'file_add' => 'excel/' . $_SESSION["think"]["auth_id"] . '/' . $error['addrs']];
                } else {
                    throw new Exception($error['msg']);
                    return ['code' => 'n', 'msg' => $error['msg']];
                }
            }
        } else {
            return ['code' => 'n', 'msg' => '记录不存在'];
        }
    }

    /**
     * 从回收站彻底删除
     */
    public function deleteforever()
    {
        $id = $this->request->param('id');
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        $result = $this->modelCompany->where($whereSql)->delete();
        $msg = $result >0 ? '彻底删除成功':'彻底删除失败';
        return ajax_return_adv($msg);
    }

    /**
     * 从回收站彻底删除
     */
    public function clear()
    {
        $id = $this->request->param('id');
        if(!empty($id)) $whereSql['id'] = $id;
        $whereSql['isdelete'] = 1;
        $result = $this->modelCompany->where($whereSql)->delete();
        $msg = $result >=0 ? '清空回收站成功':'清空回收站失败';
        return ajax_return_adv($msg);
    }
	
	 /**
     * 通过身份证找用户
     */
    public function quer_user()
    {
        $idcard = $this->request->param('idcard');
		if(empty($idcard)){
			
			return ajax_return_error('身份证号丢失'); 
		}
		$arr = ['idcard'=>$idcard];
		$userdeDetails = cur_post('serviceApi/member/getUserInfoByidcard',1,$arr,1 );
		if(!$userdeDetails->code){
			return ajax_return_error('未找到指定用户'); 
		} else {
			if(empty($userdeDetails->data->truename)){
				$msg = '您是确定添加身份证号为'.$userdeDetails->data->idcard.'的用户？';
			} else {
				$msg = '您是确定添加姓名为'.$userdeDetails->data->truename.'的用户？';
			}
			return ajax_return_adv($msg);
		}
    }
    /**
     * 传入年龄返回出生年月
     * @author sunman
     * @return array
     */
    private function returnDateString($start_age, $end_age){
        date_default_timezone_set('Asia/Chongqing'); 
        $stime = date('y');
        if(strlen($stime)!=4){
            $stime = "20".$stime;
        }

        // 获取开始年份 和结束年份区间
        if($start_age<=$end_age){

            $start_year = intval($stime-$start_age); // 开始年
            $end_year = intval($stime-$end_age); // 结束年
             
            for($i=$end_year; $i<=$start_year; $i++){
                $dateArray[] = $i;
            } 
            return $dateArray;

        }else{
            return false;
        }
        
    }

}